<template>
    <div class="m-index-wrapper" ref="indexWrapper" :style="'background-image:' + 'url('+ picList.homePage +')'">
    <!-- <div class="m-index-wrapper" ref="indexWrapper"> -->
        <div class="m-share-info">
            {{ $store.state.shareInfo.name == '' ? '我的小岛' : $store.state.shareInfo.name + '的小岛'}}
        </div>
        <confirm v-model="showPayModal"
                 :title="'充值金额'"
                 :close-on-confirm="false"
                 @on-cancel="onCancel"
                 @on-confirm="onConfirm"
        >
            <selector :value="money" title="RMB" :options="moneyList"
                      @on-change="onChange"></selector>
        </confirm>
        <confirm v-model="showCashModal"
                 :title="'金币提现(默认提现所有金币)'"
                 :close-on-confirm="false"
                 @on-cancel="onCancel1"
                 @on-confirm="onConfirm1"
        >
            <group>
                <x-input title="支付宝账号" v-model="account" placeholder="请输入支付宝账号"></x-input>
            </group>
        </confirm>
        <div class="m-property-info">
            <div class="m-left">
                <div class="m-gold" @click="cashModal">
                    <p>{{ gold }}</p>
                </div>
                <div class="m-jewel" @click="payModal">
                    <p>{{ jewel }}</p>
                </div>
            </div>
            <div class="m-right">
                <div class="m-spirit" @click="goRanking"></div>
                <div class="m-reward" @click="goDailyReward"></div>
            </div>
        </div>
        <div v-for="(island,index) in island" :key="index" class="m-island-area" :class="'m-island-' + (index + 1)"
             @click="goIsland(index+1)"></div>
    </div>
</template>


<script>
import { XInput, Confirm, Group } from "vux";

let wx = require("weixin-js-sdk");
export default {
  name: "Index",
  components: {
    XInput,
    Confirm,
    Group
  },
  data() {
    return {
      island: [1, 2, 3, 4, 5],
      id: "",
      jewel: 0,
      gold: 0,
      energyB: 0,
      energyR: 0,
      showPayModal: false,
      amount: null,
      token: "",
      pid: 0,
      money: 1,
      moneyList: [10, 30, 50, 100],
      showCashModal: false,
      account: "",
      token1: "xr5uGjGYbcqCXXUziqWOfzwPO14vMsM85SKPAnppkVQMjUHpW8yKyVZSnSou"
    };
  },
  created() {
    this.pid = window.localStorage.getItem("pid")
      ? window.localStorage.getItem("pid")
      : null;
    let userInfo = JSON.parse(window.localStorage.getItem("user"));
    this.token = window.localStorage.getItem("token");
    if (userInfo) {
      this.id = userInfo.id;
      this.jewel = userInfo.jewel;
      this.gold = userInfo.gold;
      this.energyB = userInfo.energyB;
      this.energyR = userInfo.energyR;
    }
  },
  mounted() {
    let link = "";
    let title = "标题";
    let self = this;
    this.$http
      .post("http://api.rjveg.pw/api/wechat/jssdk", { url: document.URL })
      .then(
        response => {
          let res = response.data;
          let self = this;
          wx.config({
            debug: res.debug,
            appId: res.appId,
            timestamp: res.timestamp,
            nonceStr: res.nonceStr,
            signature: res.signature,
            jsApiList: res.jsApiList
          });
          wx.ready(function() {
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
            wx.onMenuShareTimeline({
              title: "h5game", // 分享标题
              link: `http://www.rjveg.pw/${self.no}?pId=${
                self.pid ? self.pid : self.userinfo.id
              }`, // 分享链接
              imgUrl: "",
              success: function() {
                // 用户确认分享后执行的回调函数
                // self.$http.post('/index.php/weixin/Share/link',{url: document.URL}).then((response) => {
                //     let res = response.data
                // }, (response) => {})
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });
            // 朋友
            wx.onMenuShareAppMessage({
              title: "h5game", // 分享标题
              desc: "66", // 分享描述
              imgUrl: "",
              link: `http://www.rjveg.pw/${self.no}?pId=${
                self.pid ? self.pid : self.userinfo.id
              }`, // 分享链接
              type: "link", // 分享类型,music、video或link，不填默认为link
              dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
              success: function() {
                // 用户确认分享后执行的回调函数
                // self.$http.post('/index.php/weixin/Share/link', {url: document.URL}).then((response) => {
                //     let res = response.data
                //     if (res.code === '04') {
                //         return
                //     }
                // }, (response) => {})
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
                // console.log(link)
              }
            });
            wx.onMenuShareQQ({
              title: "h5game", // 分享标题
              desc: "", // 分享描述
              imgUrl: "",
              link: `http://www.rjveg.pw/${self.no}?pId=${
                self.pid ? self.pid : self.userinfo.id
              }`, // 分享链接
              success: function() {
                // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });
          });
          wx.error(p => {
            console.log(p);
          });
        },
        response => {}
      );
  },
  computed: {},
  methods: {
    cashModal() {
      this.showCashModal = true;
    },
    onCancel1() {
      this.account = "";
    },
    //             _getWxpayData() {
    //                 this.$http.get(HOST + '/api/wxpay?openid=' + this.openid).then((res) => {
    // // 这里的openid我存在了localStorage里面，获取授权进入时就进行了一次存入，方便调用。
    //                     res = res.body
    //                     if (res.status === STATUS) {
    //                         this._wxpayConfig()
    //                         wx.ready(() => {
    //                             this._setWxpayInfo(res.data)
    //                         })
    //                     }
    //                 })
    //             },
    //             _wxpayConfig() {
    //                 this.$http.get(HOST + '/api/signa').then((res) => {
    //                     console.log(res.body)
    //                     let data = res.body.data
    //                     if (res.body.status === STATUS) {
    //                         wx.config({
    //                             // debug: true,
    //                             appId: data.appId,
    //                             timestamp: data.timestamp,
    //                             nonceStr: data.nonceStr,
    //                             signature: data.signature,
    //                             jsApiList: ['chooseWXPay']
    //                         })
    //                     }
    //                 })
    //             },
    onConfirm1() {
      if (
        /^0?(13[0-9]|15[012356789]|18[0123456789]|14[0123456789]|17[0123456789])[0-9]{8}$/.test(
          this.account
        )
      ) {
        this.$http
          .get(
            "http://api.rjveg.pw/api/user/withdraw?token=" +
              this.token +
              "&alipay=" +
              this.account
          )
          .then(res => {
            let data = res.data;
            if (data.code == 200) {
              this.$vux.toast.show({
                text: data.msg,
                type: "success",
                time: 2000
              });
              this.showCashModal = false;
            } else {
              this.$vux.toast.show({
                text: data.msg,
                type: "warn",
                time: 1000
              });
            }
          });
      } else if (
        /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(
          this.account
        )
      ) {
        this.$http
          .get(
            "http://api.rjveg.pw/api/user/withdraw?token=" +
              this.token +
              "&alipay=" +
              this.account
          )
          .then(res => {
            let data = res.data;
            if (data.code == 200) {
              this.$vux.toast.show({
                text: data.msg,
                type: "success",
                time: 2000
              });
              this.showCashModal = false;
            } else {
              this.$vux.toast.show({
                text: data.msg,
                type: "warn",
                time: 1000
              });
            }
          });
      } else {
        this.$vux.toast.show({
          text: "支付宝账号格式有误",
          type: "warn",
          time: 1000
        });
        return;
      }
    },
    onChange(val) {
      this.money = val;
    },
    enCodeLocalUrl(url) {
      return window.encodeURIComponent(url); // url必须动态获取，不能缓存
    },
    share() {
      let link = this.enCodeLocalUrl(
        window.location.href.split("#")[0] + "?pId=" + this.pid
          ? this.pid
          : this.id
      );
      this.wxShare(
        "首页",
        "精灵主页",
        link,
        "https://o3e85j0cv.qnssl.com/tulips-1083572__340.jpg"
      );
    },
    onCancel() {
      this.money = 1;
    },
    randomString(len) {
      len = len || 32;
      var $chars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      var maxPos = $chars.length;
      var pwd = "";
      for (var i = 0; i < len; i++) {
        //0~32的整数
        pwd += $chars.charAt(Math.floor(Math.random() * (maxPos + 1)));
      }
      return pwd;
    },
    onConfirm() {
      // let url1 = 'http://api.ittie.cn/pay_orderid?token=' + this.token1 + this.money;

      // this.$http.get(url1).then(res => {
      //     console.log(res);
      // });
      let configUrl =
        "http://api.rjveg.pw/api/wechat/pays?token=" +
        this.token +
        "&money=" +
        this.money;
      let url =
        "http://api.rjveg.pw/api/wechat?token=" +
        this.token +
        "&money=" +
        this.money;
      this.$http.get(configUrl).then(res => {
        let data = res.data;
        let config = data.config;
        let pay = data.pay;
        this.weixinPay(config);
      });
    },
    weixinPay(data) {
      var vm = this;
      if (typeof WeixinJSBridge == "undefined") {
        //微信浏览器内置对象。参考微信官方文档
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            vm.onBridgeReady(data),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", vm.onBridgeReady(data));
          document.attachEvent("onWeixinJSBridgeReady", vm.onBridgeReady(data));
        }
      } else {
        vm.onBridgeReady(data);
      }
    },
    onBridgeReady: function(data) {
      var vm = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          debug: true,
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign //微信签名
          //这里的信息从后台返回的接口获得。
        },
        function(res) {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            if (vm.fromRoute == "personal") {
              window.location.href = document.URL;
            } else {
              // vm.confirmTry();
            }
          } else {
            alert("取消支付！");
          }
        }
      );
    },
    onHide() {
      console.log("on hide");
    },
    onShow() {
      console.log("on show");
    },
    payModal() {
      this.showPayModal = true;
    },
    goDailyReward() {
      this.$router.push({
        path: "reward"
      });
    },
    goRanking() {
      this.$router.push({
        path: "ranking"
      });
    },
    goIsland(index) {
      this.$vux.loading.show({
        text: "加载中"
      });
      setTimeout(() => {
        this.$vux.loading.hide();
        this.$router.push({
          path: "spirit/" + index
        });
      }, 1000);
    }
  }
};
</script>

<style scoped lang="less">
.m-index-wrapper {
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
}

.m-share-info {
  color: #ffbe00;
  font-size: 0.4rem;
  font-weight: 700;
  position: fixed;
  left: 50%;
  top: 0.5rem;
  transform: translateX(-50%);
}

.m-island-area {
  position: absolute;
  width: 2.5rem;
  height: 2.5rem;
}

.m-island-1 {
  left: 4.5rem;
  top: 3rem;
}

.m-island-2 {
  left: 1.5rem;
  top: 6rem;
}

.m-island-3 {
  left: 6rem;
  top: 8rem;
}

.m-island-4 {
  left: 1.5rem;
  top: 11rem;
}

.m-island-5 {
  left: 6rem;
  top: 13rem;
}
</style>
